package com.yhq.yhqproject.base.modules.board.service;

import com.yhq.yhqproject.base.common.utils.DateUtil;
import com.yhq.yhqproject.base.common.web.ListByPageResp;
import com.yhq.yhqproject.base.modules.board.entity.TemplateHistory;
import com.yhq.yhqproject.base.modules.board.entity.dto.ListLogReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TemplateHistoryService {
    @Resource
    private MongoTemplate mongoTemplate;

    public ListByPageResp<TemplateHistory> list(ListLogReq req) {
        Criteria criteria = null;
        if (req.getMd5() != null && req.getMd5().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("md5").is(req.getMd5());
            } else {
                criteria = criteria.and("md5").is(req.getMd5());
            }
        }
        if (req.getTitle() != null && req.getTitle().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("title").regex(req.getTitle());
            } else {
                criteria = criteria.and("title").regex(req.getTitle());
            }
        }
        if (req.getParams() != null && req.getParams().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("params").regex(req.getParams());
            } else {
                criteria = criteria.and("params").regex(req.getParams());
            }
        }
        if (req.getDateStr() != null && req.getDateStr().length() > 0) {
            Date d1 = DateUtil.parseDateFromString(req.getDateStr());
            Long d2 = d1.getTime();
            if (criteria == null) {
                criteria = Criteria.where("createTime").lt(d2 + 30000).gt(d2 - 30000);
            } else {
                criteria = criteria.and("createTime").lt(d2 + 30000).gt(d2 - 30000);
            }
        }

        Query query = new Query();
        if (criteria != null) {
            query = new Query(criteria);
        }

        long all = mongoTemplate.count(query, TemplateHistory.class);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        query.skip((req.getPage() - 1) * req.getSize());
        query.limit(req.getSize());
        List<TemplateHistory> list = mongoTemplate.find(query, TemplateHistory.class);
        //
        ListByPageResp<TemplateHistory> resp = new ListByPageResp<>();
        resp.setData(list);
        resp.setTotal(all);
        resp.setPage(req.getPage());
        resp.setSize(req.getSize());
        return resp;
    }
}
